package com.geeksaga.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;

import com.geeksaga.common.constant.SagaConstants;
import com.geeksaga.common.util.DateUtil;
import com.geeksaga.common.util.StringUtils;
import com.geeksaga.domain.Project;
import com.geeksaga.domain.User;
import com.geeksaga.editor.WebEditor;
import com.geeksaga.search.LuceneEngine;
import com.geeksaga.service.AuthorityService;
import com.geeksaga.service.CodeService;
import com.geeksaga.service.ProjectService;
import com.geeksaga.validator.ProjectValidator;

/**
 * @author newbie
 * @since 0.1
 */
@Controller
public class ProjectController {

    protected static final Log logger = LogFactory.getLog(ProjectController.class);
    
    @Autowired private ProjectService projectService = null;
    @Autowired private CodeService codeService = null;
    
    @RequestMapping(value = { "/project/list.do" }, method = RequestMethod.GET)
    public String list(ModelMap model, HttpServletRequest request) {

        List<Project> list = projectService.list();
        
        model.addAttribute("projectState", codeService.findCacheByPrimaryCode("B001"));
        model.addAttribute("list", (list != null) ? list : new ArrayList<Project>());
        model.addAttribute("basicDate", DateUtil.getBasicDate());
        
        return "spec/projectList";
    }
    
    @RequestMapping(value = { "/project/edit.do", "/project/modify.do", "/project/remove.do" }, method = RequestMethod.GET)
    public String setupForm(@RequestParam(required = false) String command,
            @RequestParam(required = false) String projectCode, ModelMap model, WebRequest request) {

        Project project = new Project();

        model.addAttribute("project", project);
        model.addAttribute("webEditor", WebEditor.createEditor());
        model.addAttribute("user", AuthorityService.getUser(request));
        
        if (projectCode == null) {
            model.addAttribute("project", project);
        } else {
            project.setProjectCode(projectCode);
            
//            project = projectService.find(project);
            
            model.addAttribute("project", project != null ? project : new Project());
        }
        
        return "spec/projectEdit";
    }
    
    @RequestMapping(value = { "/project/edit.do", "/project/modify.do", "/project/remove.do" }, method = RequestMethod.POST)
    public String submit(@RequestParam(required = false) String command,
            @RequestParam(required = false) String captcha, @ModelAttribute("project") Project project,
            BindingResult bindingResult, ModelMap model, HttpServletRequest request) {
        
        User user = AuthorityService.getUser(request.getSession());

        if(user != null && !StringUtils.isEmpty(user.getSid())) {
//            project.setUserSid(user.getSid());
        } else
        
        model.addAttribute("project", project);
        
        new ProjectValidator(command).validate(project, bindingResult);
        
        if(bindingResult.hasErrors()) {
            model.addAttribute("webEditor", WebEditor.createEditor());
            model.addAttribute("command", command);
               
            if(SagaConstants.ADD.equals(command))
                return "spec/projectEdit";
            else if(SagaConstants.REPLY.equals(command))
                return "spec/projectEdit";
            else if(SagaConstants.MODIFY.equals(command)) 
                return "spec/projectEdit";
            else if(SagaConstants.REMOVE.equals(command)) 
                return "spec/projectEdit";
        }
        
//        project.setEditYn(SagaConstants.USE_YES);
        
        LuceneEngine luceneEngine = LuceneEngine.getInstance();
        
        if(SagaConstants.ADD.equals(command)) {
            projectService.add(project);
            
            luceneEngine.addDocument(project.getIndexingData(), project.getProjectCode());
        } else if(SagaConstants.MODIFY.equals(command) && !StringUtils.isEmpty(project.getProjectCode())) {
//            if ((projectService.confirmPassword(project) != null) || (StringUtils.isEmpty(user.getSid()))) {
//                projectService.modify(project);

                project = projectService.findCacheByProjectCode(project.getProjectCode());
                
                luceneEngine.deleteDocument(project.getProjectCode());
                luceneEngine.addDocument(project.getIndexingData(), project.getProjectCode());
//            }
            
            model.addAttribute("project", project != null ? project : new Project());
            
            return "spec/projectView";
        } else if(SagaConstants.REMOVE.equals(command) && !StringUtils.isEmpty(project.getProjectCode())) {
            boolean isManager = (user != null && !StringUtils.isEmpty(user.getSid()) && (user.existsAuthorities("ROLE_ADMIN")));
            
            if(isManager) {
//                Service.remove(project, isManager);
                
                luceneEngine.deleteDocument(project.getProjectCode());
            } else {
                project = projectService.findCacheByProjectCode(project.getProjectCode());
                
                model.addAttribute("project", project != null ? project : new Project());
                
                return "spec/projectEdit";
            }
        }
        
        return "redirect:/project/list.do";
    }    
}